//
//  vipOrderListViewController.m
//  OrderMeal
//
//  Created by qkong on 4/23/14.
//  Copyright (c) 2014 周浩. All rights reserved.
//

#import "vipOrderListViewController.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "vipOrderTableViewCell.h"
#import "vipOrderInDetailViewController.h"
#import "UIView+Toast.h"
@interface vipOrderListViewController (){
    NSArray *orderListArray;
}
-(void)back;
@property (nonatomic,strong)UIRefreshControl *refreshControl;
@end

@implementation vipOrderListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)hudWasHidden:(MBProgressHUD *)hud{
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view addSubview:hud];
    hud.delegate = self;
    hud.labelText = @"正在加载数据";
    hud.dimBackground = YES;
    hud.mode = MBProgressHUDModeIndeterminate;
    [hud show:YES];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSNumber *memberId = [userDefaults objectForKey:@"memberID"];
    [self getVipOrderListWithUserId:[NSString stringWithFormat:@"%@",memberId]];
    // Do any additional setup after loading the view.
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //刷新tableview
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
    refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    [refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;
    
    //删除后通知刷新界面    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshForDelete:) name:@"vipOrderInDetail Delete Changed" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshForCancel) name:@"vipOrderInDetail Cancel Changed" object:nil];
}

//取消原因刷新
-(void)refreshForCancel{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSNumber *memberId = [userDefaults objectForKey:@"memberID"];
        [self getVipOrderListWithUserId:[NSString stringWithFormat:@"%@",memberId]];
    });
}

//删除原因刷新
- (void)refreshForDelete:(UITableView *)tableView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"刷新了页面");
        [self.view makeToast:@"删除成功" duration:2.0 position:@"center"];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSNumber *memberId = [userDefaults objectForKey:@"memberID"];
        [self getVipOrderListWithUserId:[NSString stringWithFormat:@"%@",memberId]];
    });
}

-(void)refreshTableView{
    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"加载中"];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [self getVipOrderListWithUserId:[userDefaults objectForKey:@"memberID"]];
    [self performSelector:@selector(afterRefresh:) withObject:nil afterDelay:0.1];
    
}

-(void)afterRefresh:(id)obj{
    [self.refreshControl endRefreshing];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
}

-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)getVipOrderListWithUserId:(NSString *)memberId
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters= @{
                                @"memberId":memberId
                                };
    
    [manager GET:orderid_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSNumber *status=responseObject[@"success"];
        
        if ([status isEqualToNumber:@1]) {
            orderListArray = responseObject[@"retData"];
            [self.tableView reloadData];
            [hud removeFromSuperview];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"该用户不存在" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [hud removeFromSuperview];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"网络错误" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ( orderListArray == nil) {
        return 0;
    }
    return [orderListArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    vipOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"vipOrderList"];
    NSInteger row = [indexPath row];
    NSDictionary *dataCell = orderListArray[row];
    //    NSLog(@"%@",responseObject[@"retData"][1][@"orderCode"]);
//    NSLog(@"%@",responseObject[@"retData"][1][@"address"]);
//    //  "status": 1,// 订单状态（ 1：待确认 2：已配送 3：完成 4：失败 9：取消）
//    
//    NSLog(@"%@",responseObject[@"retData"][1][@"status"]);
//    NSLog(@"%@",responseObject[@"retData"][1][@"turnover"]);
//    NSLog(@"%@",responseObject[@"retData"][1][@"createDate"]);

    cell.orderNum.text = dataCell[@"orderCode"];
    cell.price.text = [NSString stringWithFormat:@"￥%@",dataCell[@"turnover"]];
    cell.payDate.text = dataCell[@"createDate"];
    cell.location.text = dataCell[@"address"];
    NSNumber *statusNum = dataCell[@"status"];
    if ([statusNum isEqualToNumber:@1]) {
        cell.orderStatus.text = @"待确认";
    }else if([statusNum isEqualToNumber:@2]) {
        cell.orderStatus.text = @"已配送";
        [cell.orderStatus setTextColor:[UIColor orangeColor]];
    }else if([statusNum isEqualToNumber:@3]) {
        cell.orderStatus.text = @"已完成";
        [cell.orderStatus setTextColor:[UIColor greenColor]];
    }else if([statusNum isEqualToNumber:@4]) {
        cell.orderStatus.text = @"失败";
    }else if([statusNum isEqualToNumber:@9]) {
        cell.orderStatus.text = @"取消";
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSegueWithIdentifier:@"会员订单详情" sender:nil];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    vipOrderInDetailViewController *orderInDetail = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    int row = [indexPath row];
    orderInDetail.orderDetails = orderListArray[row];
}

@end
